import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Button } from 'antd';
import { ContentUtils } from 'braft-utils';
import UploadOSS from '@/components/UploadOSS';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import styles from './index.less';

interface EditorDemoProps {
  onHtmlContent: (content: string) => void;
  defaultContent: string;
}

const EditorDemo: React.FC<EditorDemoProps> = ({
  onHtmlContent,
  defaultContent,
}) => {
  // 创建一个空的editorState作为初始值
  const [editorState, setEditorState] = useState(
    BraftEditor.createEditorState(null),
  );

  useEffect(() => {
    if (defaultContent) {
      setEditorState(BraftEditor.createEditorState(defaultContent));
    }
  }, [defaultContent]);

  const handleSetPicURL = useCallback((value) => {
    setEditorState(
      ContentUtils.insertMedias(editorState, [
        {
          type: 'IMAGE',
          url: value,
        },
      ]),
    );
  }, []);

  const handleEditorChange = useCallback(
    (editorState: any) => {
      if (!editorState.isEmpty()) {
        setEditorState({ editorState });
        const content = editorState.toHTML();
        onHtmlContent(content);
      } else {
        onHtmlContent('');
      }
    },
    [onHtmlContent],
  );

  const extendControls = useMemo(
    () => [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <UploadOSS
            accept="image/*"
            listType=""
            maxCount={3}
            showUploadList={false}
            onSetFilesURL={handleSetPicURL}
          >
            {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
            <Button
              className="control-item button upload-button"
              data-title="插入图片"
            >
              插入图片
            </Button>
          </UploadOSS>
        ),
      },
    ],
    [handleSetPicURL],
  );

  return (
    <div className={styles.myComponent}>
      <BraftEditor
        value={editorState}
        onChange={handleEditorChange}
        extendControls={extendControls as any}
      />
    </div>
  );
};

export default EditorDemo;
